package com.onecar.carplatform.jtt.server;

import com.onecar.carplatform.jtt.config.JttNettyConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Slf4j
@Component
public class JttServer {

    @Autowired
    private JttNettyConfig jttNettyConfig;

    @Autowired
    private JttChannelHandler jttHandler;

    NioEventLoopGroup bossGroup;
    NioEventLoopGroup workerGroup;

    @PostConstruct
    public void startJttServer() throws Exception {
        bossGroup = new NioEventLoopGroup(jttNettyConfig.getBossThreadNum());
        workerGroup = new NioEventLoopGroup(jttNettyConfig.getWorkerThreadNum());
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(jttHandler)
                .option(ChannelOption.SO_BACKLOG, 1024) //服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture future = serverBootstrap.bind(jttNettyConfig.getPort()).sync();
        if (future.isSuccess()) {
            log.info("jtt tcp server start ok, port = {}", jttNettyConfig.getPort());
        }
    }

    @PreDestroy
    public void destroy() {
        bossGroup.shutdownGracefully().syncUninterruptibly();
        workerGroup.shutdownGracefully().syncUninterruptibly();
        log.info("jtt tcp server destroy");
    }
}
